#coding: utf-8
"""
    file name: BaiduVoce.py
    platform: Windows,Linux
    description: 使用Baidu REST SpeechToText完成语音到文字的转换

    module author: Guangwei Jiang (Guangwei_Jiang@wistron.com)
    Create Date: 2020/9/20

"""

import speech_recognition as sr
from aip import AipSpeech
from pyaudio import PyAudio,paInt16

class BaiduVoice:
    
    def __init__(self):
        #百度AI，配置信息
        APP_ID = '22628473'#百度ai应用id
        API_KEY = 'jOenHOG8WzfModCO9U73eDFH'#百度ai应用的键值
        SECRET_KEY = 'gw0NBWImqAo1OTupxEr6yh1Odp64n2yv'
        self.client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
        self.recordingFile = 'recording.wav'        
        
    def getFileContent(self, filePath):
        """Function to read file content

        |  Args:
        |  1. filePath: the path of the file need to read

        |  Return -- The content of the file

        >>> # read the file content
        >>> content = getFileContent("test.wav")
        """
        try:
            with open(filePath, 'rb') as fp:
                return fp.read()
        except Exception as e:
            print(e)
            return None
        
    def recordFile(self, rate=16000):
        """Function to recod the voice and save to local computer

        |  Args:
        |  1. rate: the rate of recording audio

        |  Return -- NA

        >>> # record the voice
        >>> recordFile()
        """
        try:        
            r = sr.Recognizer()
            with sr.Microphone(sample_rate=rate) as source:
                print("开始录音")
                audio = r.listen(source)#读入声音信息
 
            with open(self.recordingFile, "wb") as f:
                f.write(audio.get_wav_data())#得到wave信息写入音频文件
            print("录音完成！")
        
        except Exception as e:
            print(e)


    def speechToText(self, languageId=1537):
        """Function to get Text from Speech by using baidu Speech-To-Text service.
           For more information on Baidu REST API, check below link
           https://ai.baidu.com/ai-doc/SPEECH/1k4o0bmc7

        |  Args:
           1. languageId: language ID, please check baidu REST API interface
              1537    普通话(纯中文识别)
              1737    英语
              1637    粤语
              1837    四川话
              1936    普通话远场
              

        |  Return: The content of Speech-To-Text.

        >>> # get content of Speech-To-Text
        >>> text = speechToText()
        """
        strInput = ''
        try:
            self.recordFile()
            strInput = self.client.asr(self.getFileContent(self.recordingFile), 'wav', 16000, {'dev_pid': languageId})  # 识别本地文件
            strInput = strInput['result'][0]
            print(strInput)
        except Exception as e:
            print(e)
        finally:
            return strInput


if __name__ == "__main__":
    baiduVoice = BaiduVoice()
    baiduVoice.speechToText()
